﻿class SoundManager {
    
    public static playSound(url: string, callback: Function=null): void {
        if (!url)
            return;
      
        var audio = SoundBase.getInstance();//<HTMLAudioElement>document.getElementById("sound");
        // audio.src = url;
        // audio.onended = () => { this.sndCB()};
        audio.play(url,callback);
    }

    private static sndCB: Function;

    public static stopSound(): void {
        var audio = SoundBase.getInstance();//<HTMLAudioElement>document.getElementById("sound");
        audio.stop();
    }

    public static playBGM(url: string): void {
        if (!url)
            return;
        var audio = <HTMLAudioElement>document.getElementById("bgm");
        audio.src = url;
        audio.play();
    }

    public static stopBMG(): void {
        var audio = <HTMLAudioElement>document.getElementById("bgm");
        audio.pause();
    }

    public static playSFX(url: string): void{
        if (!url)
            return;
        var audio = <HTMLAudioElement>document.getElementById("sfx");
        audio.src = url;
        audio.play();
    }

    public static stopSFX(): void{
        var audio = <HTMLAudioElement>document.getElementById("sfx");
        audio.pause();
    }
}
class SoundBase {
    
    static _instance:SoundBase;
    
    public static getInstance() : SoundBase {
        return this._instance = this._instance || new SoundBase();        
    }
    private mainSound:egret.Sound;
    
    private mainSoundChannl:egret.SoundChannel;
    
    private isPlay:boolean;
    
    private url:string;

    private callback :Function    
    
    constructor(){
        this.mainSound = new egret.Sound();
        
        this.mainSound.addEventListener(egret.Event.COMPLETE, this.soundLoadOver,this);
        
        this.mainSound.addEventListener(egret.IOErrorEvent.IO_ERROR, function loadError(event:egret.IOErrorEvent) {
            console.log("loaded error!",this.url);
        }, this);
              
    }
    
    soundLoadOver (event:egret.Event) {
        
        if(!this.isPlay)return ;
        
        this.mainSoundChannl = this.mainSound.play(0,1);
        
        this.mainSoundChannl.addEventListener(egret.Event.SOUND_COMPLETE,function (event:egret.Event){
            this.isPlay = false;
            if (!this.callback)return ;
            this.callback();
        }, this);
    }

    
    play (url:string,callback:Function) {
        if(this.isPlay){
            this.stop()
        }
        this.url = url;
        this.isPlay = true
        this.callback = callback || this.callback; 
        this.mainSound.load(url);  
    }
    stop() {
        if(!this.mainSoundChannl || !this.isPlay)   return ;
        this.isPlay = false;
        this.mainSoundChannl.stop();   
    }
}